package cn.itcast.hotel;

import cn.itcast.hotel.constans.HotelConstants;
import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;

@SpringBootTest
public class MyHotelEsText {
    private RestHighLevelClient client;

    /**
     * 使用前连接es客户端
     */
    @BeforeEach
    void setUp() {
        this.client = new RestHighLevelClient(RestClient.builder(HttpHost.create("http://113.45.170.115:9200")));
    }

    /**
     * 使用不关闭连接
     */
    @AfterEach
    void tearDown() throws IOException {
        client.close();
    }

    /**
     * 使用java api创建es的索引
     */
    @Test
    void creatHotelIndex() throws IOException {
//        1.创建request对象
        CreateIndexRequest request = new CreateIndexRequest("hotel");
//        2.组装DSL语句(需要的数据)
        request.source(HotelConstants.MAPPING_TEMPLATE, XContentType.JSON);
//        3.发起请求
        client.indices().create(request, RequestOptions.DEFAULT);
        System.out.println("hotel 索引创建成功！！");
//        client.indices().create(new CreateIndexRequest("hotel").source(HotelConstants.MAPPING_TEMPLATE, XContentType.JSON), RequestOptions.DEFAULT);
    }

    /**
     * 查询索引，判断索引是否存在，返回的是true或false
     */
    @Test
    void testExistsHotelIndex() throws IOException {
//        1.创建获取request
        GetIndexRequest request = new GetIndexRequest("hotel");
//        2.使用exists发送请求
        boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
        System.out.println(exists ? "存在hotel索引库" : "不存在索引库！！！");
    }

    /**
     * 删除索引库
     */
    @Test
    void testDelHotelIndex() throws IOException {
//        1.创建del的请求
        DeleteIndexRequest indexRequest = new DeleteIndexRequest("hotel");
//        2.发空参请求
        client.indices().delete(indexRequest, RequestOptions.DEFAULT);
        System.out.println("=======");
    }
}